package net.xju3_4.controller;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xju3_4.common.framework.simplemvc.RequestMapping;
import net.xju3_4.common.utils.JSONUtil;
import net.xju3_4.common.utils.PageInfo;
import net.xju3_4.common.utils.Result;
import net.xju3_4.entity.Car;
import net.xju3_4.entity.CarFavorite;
import net.xju3_4.service.CarFavoriteService;
import net.xju3_4.service.CarService;
import net.xju3_4.service.impl.CarFavoriteServiceImpl;
import net.xju3_4.service.impl.CarServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@RequestMapping("/api/car")
public class CarController {

    CarService carService = new CarServiceImpl();
    CarFavoriteService carFavoriteService = new CarFavoriteServiceImpl();

    @RequestMapping("/list.do")
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String merchantIdStr = request.getParameter("merchantId");
        Integer merchantId = (merchantIdStr != null && !merchantIdStr.trim().isEmpty()) ? Integer.parseInt(merchantIdStr) : null;
        String model = request.getParameter("model");
        String brand = request.getParameter("brand");
        String licensePlate = request.getParameter("licensePlate");
        String typeIdStr = request.getParameter("typeId");
        Integer typeId = (typeIdStr != null && !typeIdStr.trim().isEmpty()) ? Integer.parseInt(typeIdStr) : null;
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        Integer pageNum = pageNumStr == null ? 1 : Integer.parseInt(pageNumStr);
        Integer pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);
        PageInfo<Car> pageInfo = carService.pageList(pageNum, pageSize,licensePlate, model, typeId, brand,merchantId);
        JSONUtil.printByJSON(response, Result.success(pageInfo));
    }

    @RequestMapping("/insert.do")
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Car car = new Car();
        request.setCharacterEncoding("utf-8");
        car.setBrand(request.getParameter("brand"));
        car.setModel(request.getParameter("model"));
        car.setColor(request.getParameter("color"));
        car.setDailyRent(new BigDecimal(request.getParameter("dailyRent")));
        car.setLicensePlate(request.getParameter("licensePlate"));
        car.setMerchantId(Integer.parseInt(request.getParameter("merchantId")));
        car.setTypeId(Integer.parseInt(request.getParameter("typeId")));
        car.setStatus(Integer.parseInt(request.getParameter("status")));
        car.setImages(request.getParameter("images"));
        carService.insert(car);
        JSONUtil.printByJSON(response, Result.success("插入成功"));
    }

    @RequestMapping("/selectOne.do")
    public void selectOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        Car car = carService.selectOne(Integer.parseInt(id));
        JSONUtil.printByJSON(response, Result.success(car));
    }

    @RequestMapping("/deleted.do")
    public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        request.setCharacterEncoding("utf-8");
        carService.deleteById(Integer.parseInt(id));
        JSONUtil.printByJSON(response, Result.success("删除成功"));
    }

    @RequestMapping("/update.do")
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Car car = new Car();
        request.setCharacterEncoding("utf-8");
        car.setBrand(request.getParameter("brand"));
        car.setModel(request.getParameter("model"));
        car.setColor(request.getParameter("color"));
        car.setId(Integer.parseInt(request.getParameter("id")));
        car.setDailyRent(new BigDecimal(request.getParameter("dailyRent")));
        car.setLicensePlate(request.getParameter("licensePlate"));
        car.setMerchantId(Integer.parseInt(request.getParameter("merchantId")));
        car.setTypeId(Integer.parseInt(request.getParameter("typeId")));
        car.setStatus(Integer.parseInt(request.getParameter("status")));
        car.setImages(request.getParameter("images"));
        System.out.println("图片的路径为"+request.getParameter("images"));
        carService.update(car);
        JSONUtil.printByJSON(response, Result.success("更新成功"));
    }

    // 车辆浏览 - 分页列表接口
    @RequestMapping("/browse.do")
    public void browse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        // 获取分页参数
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        int pageNum = pageNumStr != null ? Integer.parseInt(pageNumStr) : 1;
        int pageSize = pageSizeStr != null ? Integer.parseInt(pageSizeStr) : 10;

        // 获取筛选参数
        String brand = request.getParameter("brand");
        String typeIdStr = request.getParameter("typeId");
        String minPriceStr = request.getParameter("minPrice");
        String maxPriceStr = request.getParameter("maxPrice");

        Integer typeId = typeIdStr != null && !typeIdStr.isEmpty() ? Integer.parseInt(typeIdStr) : null;
        BigDecimal minPrice = minPriceStr != null && !minPriceStr.isEmpty() ? new BigDecimal(minPriceStr) : null;
        BigDecimal maxPrice = maxPriceStr != null && !maxPriceStr.isEmpty() ? new BigDecimal(maxPriceStr) : null;

        // 调用服务层获取车辆列表
        PageInfo<Car> pageInfo = carService.browseCarList(pageNum, pageSize, brand, typeId, minPrice, maxPrice);

        JSONUtil.printByJSON(response, Result.success(pageInfo));
    }

    // 车辆详情接口
    @RequestMapping("/detail.do")
    public void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");

        if (id == null || id.isEmpty()) {
            JSONUtil.printByJSON(response, Result.fail("车辆ID不能为空"));
            return;
        }

        Car car = carService.selectOne(Integer.parseInt(id));
        if (car == null) {
            JSONUtil.printByJSON(response, Result.fail("车辆不存在"));
            return;
        }

        JSONUtil.printByJSON(response, Result.success(car));
    }

    // 获取车辆可租日期接口
    @RequestMapping("/availability.do")
    public void getCarAvailability(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String carIdStr = request.getParameter("carId");

        if (carIdStr == null || carIdStr.isEmpty()) {
            JSONUtil.printByJSON(response, Result.fail("车辆ID不能为空"));
            return;
        }

        int carId = Integer.parseInt(carIdStr);

        // 获取车辆的不可租日期列表
        List<String> unavailableDates = carService.getUnavailableDates(carId);

        JSONUtil.printByJSON(response, Result.success(unavailableDates));
    }

    // 获取车辆类型列表
    @RequestMapping("/types.do")
    public void getCarTypes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        List<Object> carTypes = carService.getCarTypes();

        JSONUtil.printByJSON(response, Result.success(carTypes));
    }

    // ==================== 收藏相关接口 ====================

    // 添加收藏
    @RequestMapping("/favorite/add.do")
    public void addToFavorites(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        try {
            // 读取JSON请求体
            StringBuilder jsonBuilder = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            String jsonStr = jsonBuilder.toString();
            if (jsonStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("请求体不能为空"));
                return;
            }

            // 解析JSON
            Map<String, Object> data = JSON.parseObject(jsonStr, Map.class);
            Object userIdObj = data.get("userId");
            Object carIdObj = data.get("carId");
            if (userIdObj == null || carIdObj == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不完整"));
                return;
            }
            Integer userId = Integer.parseInt(userIdObj.toString());
            Integer carId = Integer.parseInt(carIdObj.toString());
            boolean success = carFavoriteService.addFavorite(userId, carId);

            if (success) {
                JSONUtil.printByJSON(response, Result.success("收藏成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("收藏失败，可能已经收藏过了"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    // 取消收藏
    @RequestMapping("/favorite/remove.do")
    public void removeFromFavorites(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        try {
            // 读取JSON请求体
            StringBuilder jsonBuilder = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            String jsonStr = jsonBuilder.toString();
            if (jsonStr.isEmpty()) {
                JSONUtil.printByJSON(response, Result.fail("请求体不能为空"));
                return;
            }
            // 解析JSON
            Map<String, Object> data = JSON.parseObject(jsonStr, Map.class);
            Object userIdObj = data.get("userId");
            Object carIdObj = data.get("carId");

            if (userIdObj == null || carIdObj == null) {
                JSONUtil.printByJSON(response, Result.fail("参数不完整"));
                return;
            }
            Integer userId = Integer.parseInt(userIdObj.toString());
            Integer carId = Integer.parseInt(carIdObj.toString());
            boolean success = carFavoriteService.removeFavorite(userId, carId);
            if (success) {
                JSONUtil.printByJSON(response, Result.success("取消收藏成功"));
            } else {
                JSONUtil.printByJSON(response, Result.fail("取消收藏失败"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    // 检查收藏状态
    @RequestMapping("/favorite/check.do")
    public void checkFavoriteStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userIdStr = request.getParameter("userId");
        String carIdStr = request.getParameter("carId");

        if (userIdStr == null || carIdStr == null || userIdStr.isEmpty() || carIdStr.isEmpty()) {
            JSONUtil.printByJSON(response, Result.fail("参数不完整"));
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);
            Integer carId = Integer.parseInt(carIdStr);
            boolean isFavorited = carFavoriteService.isFavorited(userId, carId);
            JSONUtil.printByJSON(response, Result.success(isFavorited));
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("系统错误：" + e.getMessage()));
        }
    }

    // 获取用户收藏列表
    @RequestMapping("/favorite/list.do")
    public void getUserFavorites(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String userIdStr = request.getParameter("userId");
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");

        if (userIdStr == null || userIdStr.isEmpty()) {
            JSONUtil.printByJSON(response, Result.fail("用户ID不能为空"));
            return;
        }

        try {
            Integer userId = Integer.parseInt(userIdStr);
            int pageNum = (pageNumStr != null && !pageNumStr.isEmpty()) ? Integer.parseInt(pageNumStr) : 1;
            int pageSize = (pageSizeStr != null && !pageSizeStr.isEmpty()) ? Integer.parseInt(pageSizeStr) : 10;
            PageInfo<CarFavorite> favorites = carFavoriteService.getUserFavorites(userId, pageNum, pageSize);
            JSONUtil.printByJSON(response, Result.success(favorites));
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("系统错误：" + e.getMessage()));
        }
    }
}